<?php
/**
 * Created by PhpStorm.
 * User: YAN
 * Date: 2017/6/30
 * Time: 16:15
 */

namespace App\Http\Controllers\API;


use App\Components\GetUserInfo;
use App\Components\getUsersWeiXinInfo;
use App\Http\Controllers\Controller;
use App\Models\AdminLog;
use App\Models\Classes;
use App\Models\ClassStudent;
use App\Models\CompanyUsers;
use App\Models\org\OrganizationalStructure;
use App\Models\Student;
use App\Models\StudentCourse;
use App\Models\StudentLog;
use App\Models\WeChat;
use App\Models\WechatUser;
use App\Services\College;
use App\Services\Platform;
use EasyWeChat\Foundation\Application;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class StudentController extends Controller
{
    /**
     * @param Request $request
     * @param Application $app
     * @return array|\Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function relation(Request $request,Application $app)
    {
        \DB::beginTransaction();
        try {
            $code = $request->get('u_code');
            $wx_key = $request->get('wx_key');
            $userService = $app->user;
            $userinfo = $userService->get($wx_key);
            if ($code) {
                $student = Student::query()->where('u_code',$code)
                    ->first();
                if( !$wx_key ){
                    throw new \Exception('缺少参数');
                }
                if(!$student){
                    $c = new GetUserInfo();
                    $info = $c->getUserByCode($code);
                    if (!$info) {
                        throw new \Exception('未查询到该名学生');
                    }
                    $student = new Student();
                    $student->u_name = $info->xm;
                    $student->u_code = $code;
                    $student->nick_name=$userinfo->nickname;
                    $student->head=$userinfo->headimgurl;
                    $student->wx_key = $wx_key;
                    $student->access_token =  str_random(60);
                    if (!$student->save()) {
                        throw new \Exception('绑定学生失败');
                    }
                    //student_code

                }else{
                    $student->wx_key = $wx_key;
                    $student->nick_name=$userinfo->nickname;
                    $student->head=$userinfo->headimgurl;
                    if (!$student->save()) {
                        throw new \Exception('绑定学生失败');
                    }
                }
                $joinResult = \Platform::studentJoin($wx_key,$code);
                if(!$joinResult){
                    throw new \Exception('绑定统一平台失败');
                }

            } else {
                throw new \Exception('学号不能为空');
            }
            $log = new StudentLog();
            $log->student_id = $student->id;
            $log->logs = '通过微信端绑定至服务平台';
            if(!$log->save()){
                throw new \Exception('记录添加失败');
            }
            \DB::commit();
            return ['success' => 'true','data'=>$student,'message'=>'绑定成功'];
        } catch (\Exception $e) {
            \DB::rollBack();
            return response(['success' => 'false', 'message' =>$e->getMessage()],406);
        }
    }

    /**
     * @param Request $request
     * @return array|\Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     * @throws \Exception
     */

    public function relieve(Request $request){
        $wx_key = $request->get('wx_key');
        $student = Student::query()->where(['wx_key'=>$wx_key])->first();
        if($student){
            $student->wx_key = null;
            $student->nick_name=null;
            $student->head = null;
            $student->save();
            $log = new StudentLog();
            $log->student_id = $student->id;
            $log->logs = '解除了绑定';
            if(!$log->save()){
                throw new \Exception('记录添加失败');
            }
            $relieve = \Platform::relieve($wx_key);
            if(!$relieve){
                throw new \Exception('解绑失败');
            }
            return ['success'=>'true','message'=>'解绑成功'];
        }else{
            return response(['success' => 'false', 'message' => '未找到该用户'],406);
        }

    }

    /**
     * @param Request $request
     * @return array|\Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function info(Request $request){
        $wx_key = $request->get('wx_key');
        $student = Student::query()->where(['wx_key'=>$wx_key])->first();
        if($student){
            return ['success'=>'true','message'=>'查询成功','data'=>  $student];
        }else{
            return response(['success' => 'false', 'message' => '未找到该用户'],406);
        }
    }

    /**
     * @return array
     */
    public function getList()
    {
        $students = Student::query()->get();
        $result = [];
        if ($students) {
            foreach ($students as $items) {
                $result[$items->id] = $items->u_name;
            }
        }
        return $result;
    }

    /**
     * @param Request $request
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function index(Request $request)
    {
        $queryString = $request->get('query', '');
        $models = Student::with('teach','business')
            ->where('u_name', 'like', '%' . $queryString . '%')
            ->orWhere('u_code', 'like', '%' . $queryString . '%')
            ->paginate();
        return $models;
    }

    /**
     * @param Request $request
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function studentSearch(Request $request)
    {
        $org = $request->get('query','');
        $id= DB::table('organizational_structures')->select('jcbid')->where('level_tab','like','%'.$org.'%')->pluck('jcbid')->toArray();
        $id = array_filter($id);
        $models = Student::query()
            ->whereIn('teach_class',$id)
            ->paginate();
        return $models;
    }


    /**
     * 添加学生
     * @param Request $request
     * @return mixed
     */
    public function store(Request $request)
    {
        $model = new Student();
        $model->fill($request->all());
        if ($model->save()) {
            return $model;
        } else {
            return response($model->getErrors()->toArray(), 406);
        }
    }


    /**
     * 修改员工
     * @param User $User
     * @param Request $request
     * @return mixed
     */
    public function update(Student $student, Request $request)
    {
        $student->fill($request->all());
        if ($student->save()) {
            return $student;
        } else {
            return response($student->getErrors()->toArray(), 406);
        }
    }


    /**
     * 删除
     * @param $id
     * @return mixed
     */
    public function destroy($id)
    {
        $model = $this->findModel($id);
        try {
            $logs = new AdminLog();
            $logs->admin = Auth::user()->id;
            $logs->logs = '删除学生信息：'. $model->u_name;
            if (!$logs->save()) {
                throw new \Exception('记录保存失败');
            }
            $model->delete();
            return ['state' => 'success'];
        } catch (\Exception $e) {
            return ['state' => 'failed', 'message' => $e->getMessage()];
        }
    }


    /**
     * 返回单个实例
     * @param User $user
     * @return mixed
     */
    public function show(Student $student)
    {
        return $student;
    }


    /**
     * @param $id
     * @return Staff
     */
    public function findModel($id)
    {
        $model = Student::findOrFail($id);
        return $model;
    }


}